package com.susu.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.susu.entity.Book;
import com.susu.service.impl.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.WeakHashMap;

@Controller
public class BookController {

    @Autowired
    private BookServiceImpl bookServiceImpl;

    @GetMapping("/getBooks")
    public String getBooks(@RequestParam(defaultValue = "1") Integer pageNum, Book book, Model model) {
        Page<Book> page = new Page<Book>(pageNum, 3);

        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (book.getName() != null && !book.getName().equals("")) {
            wrapper.like("name", book.getName());
        }

        if (book.getCategory() != null && !book.getCategory().equals("")) {
            wrapper.like("category", book.getCategory());
        }

        if (book.getAuthor() != null && !book.getAuthor().equals("")) {
            wrapper.like("author", book.getAuthor());
        }

        List<Book> list = bookServiceImpl.list(page, wrapper);
        model.addAttribute("list", list);
        model.addAttribute("page", page);
        model.addAttribute("book", book);
        return "bookList";
    }


    //批量删除
    @PostMapping("/del")
    public String delBooks(Integer[] ids){
        List list = Arrays.asList(ids);
        bookServiceImpl.removeBatchByIds(list);
        return "redirect:/getBooks";
    }

    //to add page
    @GetMapping("/toAddPage")
    public String toAddPage(){
        return "addBooks";
    }

    //添加
    @PostMapping("/addBook")
    public String addBook(Book book){
        book.setSales(0);
        bookServiceImpl.save(book);
        return "redirect:/getBooks";
    }
}
